package com.seraph.td.socket;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Root {
  private static boolean exitFlg = true;
static public void main(String[] argv){
	  System.out.println("BEGIN RECEIVE.............");
	 receive();
	  System.out.println("END RECEIVE.............");
//	  In
  }
	static void receive(){
		ServerSocket socket = null;
		InputStream in = null;
		ByteArrayOutputStream out = null ;
		try {
			socket = new ServerSocket(8199);
			while(true){
				byte[] buffer = new byte[1024];
				out = new ByteArrayOutputStream();
				Socket rmoteSocket = socket.accept();
				System.out.println("test getInetAddress().getHostAddress()");
				System.out.println(rmoteSocket.getInetAddress().getHostAddress());
				System.out.println("test getInetAddress().getHostAddress()");
				if(exitFlg )
					return;
				in = rmoteSocket.getInputStream();
				File file = new File("seraph.mp4");
				if(file.exists()) file.delete();
				file.createNewFile();
				int length = in.read(buffer);
				while(length != -1){
					out.write(buffer);
					if(out.size() > 1024*1024) {
						writeToFile(file ,out);
						out.reset();
					}
					length = in.read(buffer);
				}
				writeToFile(file,out);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private static void writeToFile(File file,ByteArrayOutputStream out) {
		// TODO Auto-generated method stub
		try{
		BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(file,true));
		ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
		byte[] buffer = new byte[1024];
		int len  = in.read(buffer);
		while(len != -1){
			fout.write(buffer, 0, len);
			len  = in.read(buffer);
		}
		fout.close();
		in.close();
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
}
